package com.hqyj.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.mapper.OrderMapper;
import com.hqyj.mapper.PaymentMapper;
import com.hqyj.mapper.TicketMapper;
import com.hqyj.pojo.*;
import com.hqyj.serviceInf.OrderServiceInf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderServiceInf {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private TicketMapper ticketMapper;
    //全查
    @Override
    public Map<String, Object> selectAll(int pageNum, int pageSize, String username) {
       //开启分页
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = orderMapper.selectAll(username);
        PageInfo<User> orderPageInfo = new PageInfo<>(list);
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("orderPageInfo",orderPageInfo);
        return map;
    }
//查询一个
    @Override
    public Order selecOrderByOrderid(int orderid) {
        return orderMapper.selectOrderByOrderid(orderid);
    }

    //添加
    @Override
    public int insertOrder(Order order) {
        int flag = orderMapper.insertOrder(order);
//      添加成功，添加支付信息，状态为未支付
        if(flag > 0){
//            查询订单id并设置，用于关联支付表
            order.setOrderid(orderMapper.selectOrderIdByOrderInfo(order));
//            创建payment对象
            Payment payment = new Payment();
//            添加订单id
            payment.setOrderid(order.getOrderid());
//            订单创建时间
            payment.setPaymenttime(order.getOrdertime());
//            默认为订单价格（实际支付价格可能发生改变）
            payment.setPaymentmount(order.getSumprice());
//            订单创建时默认未支付
            payment.setPaymentstatus(0);
            Ticket ticket = ticketMapper.showTicketById(order.getTicketid());
//            票余量不够订单购买票的数量
            if(ticket.getTicketnum() <= order.getNum()){
                flag = -1;
//                删除已创建的订单
                orderMapper.deleteOrder(order.getOrderid());
            }else {
//                票余量减去订单购买数量
                Ticket ticket1 = new Ticket(ticket.getTicketid(), ticket.getTicketname(),
                        ticket.getPrice(), ticket.getTicketsum(), ticket.getTicketnum() - order.getNum());
//                修改数据库余量
                ticketMapper.updateTicket(ticket1);
//                创建支付订单
                paymentMapper.insertPayment(payment);
            }
        }
        return flag;
    }
   //修改
    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }
    //删除
    @Override
    public int deleteOrder(int orderid) {
        int flag = orderMapper.deleteOrder(orderid);
        return flag;
    }
}
